package com.decent.util;


import com.alibaba.fastjson.JSON;
import com.decent.constant.Constant;
import com.decent.entity.GetOrderEntity;
import com.decent.entity.Order;
import com.decent.entity.common.Message;
import com.decent.service.OrderService;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class ScheduledGetOrder {

    public void getOrder(OrderService orderService) {

        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        /*
         *         周期性执行任务
         *             参数1：任务
         *             参数2：延迟时长数字（第一次在执行上面时间以后）
         *             参数3：周期时长数字（没隔多久执行一次）
         *             参数4：时长数字的单位
         */
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
//                GetOrderEntity entity = new GetOrderEntity(Constant.SUP_ID, 1, System.currentTimeMillis() + "");
                GetOrderEntity entity = new GetOrderEntity();
                System.out.println(entity);
                String response = HttpUtil.tyfhPost(entity);
                Message message = JSON.parseObject(response, Message.class);
                Order order = messageToOrder(message);

                Long orderNoCount = orderService.getOrderNoCount(order.getOrderNo());
                System.out.println("orderNoCount=" + orderNoCount);
                if (orderNoCount == 0) {
                    Integer integer = orderService.insertOrder(order);
                    System.out.println("aaa=" + integer);
                }

                // System.out.println(Thread.currentThread().getName()+"锄禾日当午");

            }
        },1,3, TimeUnit.SECONDS);
    }

    private static Order messageToOrder(Message message) {
        String data = message.getData().toString();
        String substring = data.substring(1, data.lastIndexOf("]"));
        Order order = JSON.parseObject(substring, Order.class);
        System.out.println(order);
        return order;
    }
}
